//
//  YHRefreshHeader.m
//  UniversalApp
//
//  Created by 胡双喜 on 2018/6/29.
//  Copyright © 2018年 邓超. All rights reserved.
//

#import "YHRefreshHeader.h"
@interface YHRefreshHeader()
@property (nonatomic, strong) NSArray *gifs;
@property (nonatomic, strong) UIImageView *bgImg;
@property (nonatomic, strong) UIImageView *gifImg;
@property (nonatomic, strong) CABasicAnimation *bgAnimation;
@end

@implementation YHRefreshHeader

- (void)prepare
{
    [super prepare];
    self.bgImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refresh_bubble"]];
    [self addSubview:self.bgImg];
    
    
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=3; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"refresh_%zd", i]];
        [idleImages addObject:image];
    }
    self.gifs = idleImages;
    self.gifImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refresh_1"]];
    self.gifImg.animationImages = idleImages;
    self.gifImg.animationDuration = 0.5;
    [self addSubview:self.gifImg];
    
}

- (void)placeSubviews
{
    [super placeSubviews];
    CGSize size = [UIImage imageNamed:@"refresh_bubble"].size;
    CGFloat s = size.height / self.mj_h;
    CGFloat width = size.width / s;
    self.bgImg.frame = CGRectMake((self.mj_w - width)/2, 0, width, self.mj_h);
    
    
    size = [UIImage imageNamed:@"refresh_1"].size;
    CGFloat height = self.mj_h - 4;
    s = size.height / height;
    width = size.width / s;
    
    
    self.gifImg.frame = CGRectMake((self.mj_w - width)/2, 2, width, height);
    
    CABasicAnimation *bgAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    bgAnimation.fromValue = @(self.mj_w);;
    bgAnimation.toValue = @(-self.mj_w);
    bgAnimation.duration = 2.0;
    bgAnimation.repeatCount = CGFLOAT_MAX;
    self.bgAnimation = bgAnimation;
    
}

- (void)setPullingPercent:(CGFloat)pullingPercent
{
    [super setPullingPercent:pullingPercent];
    if ( !(self.state == MJRefreshStateIdle || self.state == MJRefreshStatePulling) || self.gifs.count == 0) return;
    [self.gifImg stopAnimating];
    
    NSInteger count = self.gifs.count;
    NSUInteger index =  count * (pullingPercent * 10);
    
    self.gifImg.image = self.gifs[index % count];
}

- (void)setState:(MJRefreshState)state
{
    MJRefreshCheckState
    if (state == MJRefreshStateRefreshing)
    {
        [self.gifImg stopAnimating];
        [self.bgImg.layer removeAllAnimations];
        
        [self.gifImg startAnimating];
        [self.bgImg.layer addAnimation:self.bgAnimation forKey:nil];
    }
    else if (state == MJRefreshStateIdle)
    {
        [self.gifImg stopAnimating];
        [self.bgImg.layer removeAllAnimations];
    }
}


@end

